﻿// ע�


using EcsDebugSimulator.Models;
using EcsDebugSimulator.Services.SimulatorHandle;
using Microsoft.Extensions.DependencyInjection;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Sockets;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using XT.MNet.Helpers;
using XT.MNet.Tcp;
using XT.MNet.Tcp.Options;
using static System.Runtime.InteropServices.JavaScript.JSType;

namespace EcsDebugSimulator.Services.SimulatorHandle;
public class EquipSimulatorOperation 
{

    public event EventHandler<string> Receive;

    public event EventHandler<string> Send;

    private IServiceProvider _provider;

    private CancellationTokenSource _cancellationTokenSource;

    private bool _status = false;

    private TcpServer _sendServer;

    private TcpServer _recieveServer;

    private SimulatorHandleBase _simulatorHandle;


    public EquipSimulatorOperation()
    {
    }

    public void Dispose()
    {
        throw new NotImplementedException();
    }


    public bool GetOperationStatus()
    {
        return _status;
    }

    public async Task<bool> Init(string ip, int port, CommandContent comContent,string equipType)
    {
        try
        {
        
            // 获取设备对应的处理器
            _simulatorHandle = Register.App.GetRequiredKeyedService<SimulatorHandleBase>("Simulator");

            //创建一个Socket服务端
            _recieveServer = new TcpServer(new TcpServerOptions()
            {
             
                Address = ip,
                Port = (ushort)port,
                //Logger = debugLogger, // ILogger of your liking, default is just console one
                SpecialChar = '#' // only work for raw data
            });
          
            _recieveServer.On((data, conn) => {

                string recieve = Encoding.UTF8.GetString(data.ToArray());
                Receive.Invoke(null, recieve);
                _simulatorHandle.HandleData(recieve, comContent, equipType);

            });
            _simulatorHandle.SendMsgEvent += _simulatorHandle_SendMsgEvent;
            //添加断开连接事件
            if (_recieveServer != null)
            {
                _recieveServer.OnConnect += _recieveServer_OnConnect;
                _recieveServer.OnDisconnect += _recieveServer_OnDisconnect;
            }

            _recieveServer.Start();
            //_sendServer.Start();
           

        }
        catch (Exception ex)
        {
           
     
            return false;
        }
        Send.Invoke(null, "开启Socket服务");
        return true;
    }

    private void _simulatorHandle_SendMsgEvent(object? sender, SimulatorGeneralDto e)
    {
        var result = _simulatorHandle.MsgHandle(e);

        var sendData = Encoding.UTF8.GetBytes(result);

        _recieveServer.Broadcast(sendData);

        Send.Invoke(null, result);
    }

    private void _sendServer_OnDisconnect(TcpServerConnection connection)
    {
        Send.Invoke(null, "客户端已断开连接");
    }

    private void _sendServer_OnConnect(TcpServerConnection connection)
    {
        Send.Invoke(null, "客户端已连接");
    }



    /// <summary>
    /// 断开事件
    /// </summary>
    /// <param name="connection"></param>
    /// <exception cref="NotImplementedException"></exception>
    private void _recieveServer_OnDisconnect(TcpServerConnection connection)
    {
        Send.Invoke(null, "客户端已断开连接");
    }

    /// <summary>
    /// 连接事件
    /// </summary>
    /// <param name="connection"></param>
    /// <exception cref="NotImplementedException"></exception>
    private void _recieveServer_OnConnect(TcpServerConnection connection)
    {
        Send.Invoke(null, "客户端已连接");
    }

    public async Task  OperationStart()
    {
     
      
    }

    public async Task<bool> OperationStop()
    {
        try
        {
            _status = false;
            _recieveServer?.Stop();
        }
        catch
        {
            return false;
        }  

          return true;
    }

    public async Task<bool> WriteRequest(string writeInfo)
    {
        try
        {
            if (writeInfo !=null )
            {
                var sendData = Encoding.UTF8.GetBytes(writeInfo);
                _recieveServer.Broadcast(sendData);
                Send.Invoke(this, writeInfo);
            }
        }
        catch
        {
            return false;
        }
        return true;
    }


    private void CancelPolling()
    {
        if (_cancellationTokenSource != null)
        {
            _cancellationTokenSource.Cancel();
            _cancellationTokenSource.Dispose();
            _cancellationTokenSource = null;
        }
    }
}
